<template>
	<div>
		<div style="padding:10px 0;">
			<span style = "font-weight:550;">监测点列表</span>
			<div style="float:right;margin-top: -4px;" v-if="['查看模板','模板审核','任务详情','任务签发'].indexOf(title)<0">
				<el-button type="primary" size="mini" @click="copySample">复制</el-button>
				<el-button type="primary" size="mini" @click="addPoint">添加点位</el-button>
				<el-button :type="editDisable?'primary':'success'" size="mini" @click="addNextPoint()">添加质控</el-button>
				<el-button type="primary" size="mini" @click="editBottle" :disabled="editDisable" v-if="getPlanData.status !='502' ">采样设置</el-button>
				<el-button type="primary" size="mini" @click="deletePoint" :disabled="editDisable">删除</el-button>
			</div>
			<div v-if="title == '任务签发'" style = "float:right;display:inline-block">
				<div class = "tipMessage">新增:<span class = "colorgreen isSpan" ></span></div>
				<div class = "tipMessage">修改:<span class = "colorBlue isSpan"></span></div>
				<div class = "tipMessage">删除:<span class = "colorgrey isSpan"></span></div>

			</div>
		</div>
		<!--{{typeQcSelect.itemList}}-->
		<el-table v-if="sampleShow" :data="getPlanData.sampleBeans" style="width: 100%;margin-top:8px;" size="mini" :height="tableHeightC"
		 @current-change="currentChange" highlight-current-row @selection-change="handleSelectionChange" class='tablegrey' ref="sampleTable"
		 :row-class-name="rowClassName">
			<el-table-column type="selection" min-width="38px" :selectable='selectInit' key="selection" v-if="['查看模板','任务详情','任务签发'].indexOf(title)<0"
			 fixed>
			</el-table-column>
			<el-table-column min-width="80px" label="序号">
				<template slot-scope="scope">
					{{scope.$index+1}}
				</template>
			</el-table-column>
			<el-table-column property="name" label="名称" min-width="120px"  show-overflow-tooltip>
			</el-table-column>

			<el-table-column min-width="150px" property="monitorZoneName" label="监测区域" show-overflow-tooltip>

			</el-table-column>

			<el-table-column property="monitorName" min-width="100px" label="监测点" show-overflow-tooltip>
			</el-table-column>

			<el-table-column property="collectionMan" min-width="80px" label="采样人" :formatter="collectionFormatter">
			</el-table-column>
			<el-table-column property="collectionLeader" min-width="120px" label="现场负责人" :formatter="collectionFormatter">
			</el-table-column>
			<!--<el-table-column
                v-if="!isBD"
                min-width="220px"
                label="采样容器"
                >

                <template slot-scope="scope">
                    {{'玻璃瓶-250ml、塑料瓶-500ml'}}
                </template>
              </el-table-column>-->
			<el-table-column property="qcType" min-width="100px" label="QC类型" :formatter="qcTypeFormatter">
			</el-table-column>
			<!--<el-table-column
                property="parent"
                min-width="160px"
                label="父样编号"
                >
              </el-table-column>-->
			<!--<el-table-column
                  label="操作"
                  min-width="130px"
                  fixed="right"
                  :key="Math.random()"
                  v-if="['查看模板','任务详情','任务签发'].indexOf(title)<0"
                  >
                  <template slot-scope="scope">
                    <el-button
                    	 type="text" size="mini" :disabled="!scope.row.qcType" @click="editPoint(scope.row)">更改</el-button>

                  </template>
              </el-table-column>-->
		</el-table>
		<!--<div v-if="isshowAddBottle">

		    </div>-->
		<add-bottle :showAddBottle.sync="isshowAddBottle" :selectedArr.sync="monitorPoints"></add-bottle>

		<addPoint ref="addPointChild" :selectedArr="monitorPoints" :currentArr="currentArr" :showAddpoint.sync="isShowAddpoint" :addPointTitle.sync="addPointTitle"
		 :sampleForm.sync="sampleForm" :addIndex.sync="addIndex" :client.sync="getPlanData.client"></addPoint>
	</div>
</template>

<script>
	import { mapState } from 'vuex'
	import addBottle from './dialog/addBottle'
	import addPoint from './dialog/addPoint'
	export default {
		components: {
			addBottle,
			addPoint
		},
		props: ['title', 'getPlanData'],
		data() {
			return {
				sampleShow: true,
				addIndex: '',
				sampleForm: {},
				addPointTitle: '',
				editDisable: true,
				isShowAddpoint: false,
				isshowAddBottle: false,
				monitorPoints: [],
				allMonitorZone: [],//获取所有检测区域信息
				allMonitor: [],//所有监测点的信息
				currentArr: []//当前高亮信息
			}
		},
		computed: {
			...mapState(['status', 'isBD', 'typeQcSelect', 'EmployeeByLabs', 'monitorSelect', 'QCS', 'QCS1', 'areaoptions']),
			tableHeightC(){
				return ((window.innerHeight - 300) / 2 - 5) //有上下两个表格
			}
		},
		mounted() {
			console.log(this.getPlanData)
			this.$nextTick(() => {
				this.typeQcSelect.itemList = [...this.QCS, ...this.QCS1]
			})
			if(this.getPlanData.sampleBeans.length > 0){
				this.setSampleCurrent(this.getPlanData.sampleBeans[0])
			}

			if (this.getPlanData.client) {
				this.$store.dispatch('getMonitorZones', this.getPlanData.client)
			}
			this.$store.dispatch('getEmployeeByLab')
			this.$store.dispatch('getAllSubcontractor')

			this.getallMonitor()

		},
		watch: {
			monitorPoints: {
				handler: function (newValue, oldValue) {
					if (this.monitorPoints.length != 0) {
						this.editDisable = false
					} else {
						this.editDisable = true
					}
				},
				deep: true
			},
			'currentArr.detectBeans':{
				handler(newValue) {
					this.selectInit(this.currentArr)

				},

			}

		},

		methods: {
			selectInit(row, index) {
				if(row.detectBeans != undefined && row.detectBeans.length == 0){ //如果没有检测项目  可以删除
					return true  //可勾选
				}else{
					// 待领取状态之后的 不可设置 编辑 删除
					if (this.getPlanData.status == 502 || this.getPlanData.status == 4) {// 如果任务状态时检测中的话，才需要控制样品状态
						if (row.status > 513) {
							return false  //不可勾选
						} else {
							return true  //可勾选
						}
					} else {
						return true  //可勾选
					}
				}

			},
			reload() {
				this.sampleShow = false;
				this.$nextTick(() => {
					this.sampleShow = true;
				})
			},
			monitorZoneFormatter(row, column, cellValue, index) {
				let filterArr = [];
				filterArr = this.areaoptions.filter(item => item.id === cellValue)
				if (filterArr.length != 0) {
					return filterArr[0].name
				}

			},
			monitorFormatter(row, column, cellValue, index) {
				let filterArr = [];
				filterArr = this.allMonitor.filter(item => item.id === cellValue)
				if (filterArr.length != 0) {
					return filterArr[0].name
				}
			},
			monitorTypeFormatter(row, column, cellValue, index) {

				let filterArr = [];
				filterArr = this.monitorSelect.itemList.filter(item => item.code === cellValue)
				if (filterArr.length != 0) {

					return filterArr[0].name
				}


			},
			//			格式化人员
			collectionFormatter(row, column, cellValue, index) {
				let filterArr = [];
				filterArr = this.EmployeeByLabs.filter(item => item.account === cellValue)
				if (filterArr.length != 0) {
					return filterArr[0].name
				}else{
					return "---"
				}

			},
			//			格式化qc值
			qcTypeFormatter(row, column, cellValue, index) {
				let filterArr = []

				filterArr = this.typeQcSelect.itemList.filter(item => item.code === cellValue)
        // console.log(filterArr)
				if (filterArr.length != 0) {
					return filterArr[0].name
				}else{
					return "---"
				}

			},

			rowClassName({ row, rowIndex }) {
				if (this.getPlanData.status == "501") {
					// 1代表新增
					if (row.updateFlag === 1) {
						return 'colorgreen'
					}
					// 2代表删除
					if (row.updateFlag === 2) {
						return 'colorgrey'
					}
					// 3代表修改
					if (row.updateFlag === 3) {
						return 'colorBlue'
					}
				}

			},
			//			获取所有监测点
			getallMonitor() {
				this.$http({
					method: 'post',
					apiUrl: '/client/readMonitors.htm',
					params: { fRef: '', id: this.getPlanData.client },
					isJson: true,
				}).then(res => {
					if (res.code === 0) {

						this.allMonitor = res.data
					} else {
						//				          	reject(err)
					}
				}, )


			},
			// 点击监测点，显示改监测点下的能力参数和检测项目
			setSampleCurrent(row) {
				this.$refs.sampleTable.setCurrentRow(row);

				//当创建模板和任务是设置默认容器
				if (row.detectBeans != undefined) {
					let detectBeans = row.detectBeans
					let params = detectBeans.map((item) => { return { detectability: item.detectability } })
					// this.$parent.planHandleBottle(params).then((res) => {

					// 	row.bottle = res.data
						this.passData2Brother(row)
					// })
				}else{
					row.bottle = '';
					this.passData2Brother(row)
				}

			},


			passData2Brother(passData) {
				this.$root.eventHub.$emit("sample2brother", passData)
			},
      // 复制
      copySample(){

        if(this.monitorPoints.length > 1 || this.monitorPoints.length == 0){
          this.$message({
            type:"warning",
            message:"请勾选一个样品!",
          })
          return
        }else{
          if(this.monitorPoints[0].qcType != "" && this.monitorPoints[0].qcType != null && this.monitorPoints[0].qcType != undefined){
            this.$message({
              type:"warning",
              message:"质控样品不能复制!",
            })
            return
          }else{
            this.addPointTitle = '复制'
            this.isShowAddpoint = true;

            this.sampleForm = {
            	bottleTypeNumber: null,
            	collectionLeader: "",
            	collectionLeaderName: "",
            	collectionMan: "",
            	collectionManName: "",
            	createBy: "",
            	createTime: "",
            	fRef: "",
            	id: "",
            	laboratory: "",
            	monitor: [],
            	monitorName: "",
            	monitorType: "",
            	monitorZone: "",
            	monitorZoneName: "",
            	name: "",
            	qcType: "",
            	detectBeans: [],
            	detailBeans: []
            }
            for(let i in this.monitorPoints[0]){
              if(i == 'detectBeans' || i == 'detailBeans' || i == 'collectionLeader' ||
              i == 'collectionLeaderName' || i == 'collectionMan' || i == 'collectionManName'){
                this.sampleForm[i] = JSON.parse(JSON.stringify(this.monitorPoints[0][i]));
              }
            }
            if(this.sampleForm.detectBeans.length > 0){
              this.sampleForm.detectBeans.forEach((item) =>{
                  delete item.status;
                  delete item.id;
                  delete item.deleteFlag;
                  item.itemBeans.forEach((item1) =>{
                    delete item1.status;
                    delete item1.id;
                  })
              })
            }
            console.log(this.sampleForm)

          }

        }
      },
			addPoint() {
				this.addPointTitle = '添加'
				this.isShowAddpoint = true;
				this.sampleForm = {
					bottleTypeNumber: null,
					collectionLeader: "",
					collectionLeaderName: "",
					collectionMan: "",
					collectionManName: "",
					createBy: "",
					createTime: "",
					fRef: "",
					id: "",
					laboratory: "",
					monitor: [],
					monitorName: "",
					monitorType: "",
					monitorZone: "",
					monitorZoneName: "",
					name: "",
					qcType: "",
					detectBeans: [],
					detailBeans: []
				}
			},
			deletePoint() {
				var deleMonitors = [];//选出所有需要删除的监测点（样品）
				for (let j = 0; j < this.monitorPoints.length; j++) { //遍历每一个勾选的监测点

					if (this.monitorPoints[j].qcType == null || this.monitorPoints[j].qcType == undefined || this.monitorPoints[j].qcType == "") { //如果质控类型为空，则为父样，则需找到子样删除
						for (let i = 0; i < this.getPlanData.sampleBeans.length; i++) {
							if ( this.getPlanData.sampleBeans[i].parent == this.monitorPoints[j].parent) { //找到子样
								deleMonitors.push(this.getPlanData.sampleBeans[i]);
							}
						}
					}else{
						deleMonitors.push(this.monitorPoints[j]); //不管勾选的是不是父样都要把自己本身加入
					}

				}
				deleMonitors.forEach(item => {

					this.getPlanData.sampleBeans.splice(this.getPlanData.sampleBeans.indexOf(item), 1)
				})
				if(this.getPlanData.sampleBeans.length > 0){
					this.currentChange(this.getPlanData.sampleBeans[0])
				}else{
					this.currentChange()
				}


			},
			editPoint(row) {
				console.log(row)
				this.$refs.addPointChild.readMonitors(row)
				this.sampleForm = row
				this.addPointTitle = '更改'
				this.isShowAddpoint = true;
			},
			addNextPoint() {

				//		       console.log(this.monitorPoints)

				this.sampleForm = {
					bottleTypeNumber: null,
					collectionLeader: "",
					collectionLeaderName: "",
					collectionMan: "",
					collectionManName: "",
					createBy: "",
					createTime: "",
					fRef: "",
					id: "",
					laboratory: "",
					monitor: "",
					monitorName: "",
					monitorType: "",
					monitorZone: "",
					monitorZoneName: "",
					name: "",
					qcType: "",
					detectBeans: [],
					detailBeans: []
				}
				this.addPointTitle = '添加现场质控'
				this.isShowAddpoint = true;

				//
				//		       this.addPointTitle = '添加'
				//		       this.isShowAddpoint = true;

				//
			},
			handleSelectionChange(val) {
				this.monitorPoints = val;
			},
			currentChange(val) {
				this.currentArr = val
				if (val == undefined || val == null) {
					this.currentArr = {};
				}
				this.setSampleCurrent(this.currentArr)
			},
			editBottle() {
				this.isshowAddBottle = true
			}
		},

	}

</script>

<style>
	.tablegrey .colorgreen {
		color: aqua;
	}

	.tablegrey .colorgrey {
		color: #ccc;
	}

	.tablegrey .colorBlue {
		color: #409eff
	}
	.tipMessage{
		display:inline-block;
		line-height: 35px;
		margin-left: 8px;

	}
	.isSpan{
		display:inline-block;
		width:20px;
		height:20px;
		border-radius: 2px;
		vertical-align: middle;
		margin-left:5px;

	}
	.isSpan.colorgreen{
		background:aqua
	}
	.isSpan.colorgrey{
		background:#ccc
	}
	.isSpan.colorBlue{
		background:#409eff
	}

</style>
